package StringDemo;

import static java.lang.Integer.parseInt;
import static java.lang.Math.max;

/**
 * 给你两个二进制字符串 a 和 b ，以二进制字符串的形式返回它们的和。
 * 示例 1：
 * 输入:a = "11", b = "1"
 * 输出："100"
 */
public class demo67 {
    public static void main(String[] args) {
        String a = "11";
        String b = "1";
        System.out.println(addBinary(a, b));
    }
    //先补0，然后从后往前加，减少编写晦涩的代码判断长短
    public static String addBinary(String a, String b) {
        String res = "";
        int carry = 0;
        int i = a.length() - 1, j = b.length() - 1;
        while(i<j){
            a = "0" + a;
            i++;
        }
        while (i>j){
            b = "0" + b;
            j++;
        }
        for (; i >= 0 && j >= 0; i--, j--) {
            if (a.charAt(i) + b.charAt(j) - '0' - '0' + carry == 2) {
                res = "0" + res;
                carry = 1;
            } else if (a.charAt(i) + b.charAt(j) - '0' - '0' + carry == 3) {
                res = "1" + res;
                carry = 1;
            } else if (a.charAt(i) + b.charAt(j) - '0' - '0' + carry == 1) {
                res = "1" + res;
                carry = 0;
            } else {
                res = "0" + res;
                carry = 0;
            }
        }
        if(carry==1) return "1" + res;
        return res;
    }

/*    public static String addBinary0(String a, String b) {
        String res = "";
        int carry = 0;
        int i = a.length() - 1, j = b.length() - 1;
        for (; i >= 0 && j >= 0; i--, j--) {
            if (a.charAt(i) + b.charAt(j) - '0' - '0' + carry == 2) {
                res = "0" + res;
                carry = 1;
            } else if (a.charAt(i) + b.charAt(j) - '0' - '0' + carry == 3) {
                res = "1" + res;
                carry = 1;
            } else if (a.charAt(i) + b.charAt(j) - '0' - '0' + carry == 1) {
                res = "1" + res;
                carry = 0;
            } else {
                res = "0" + res;
                carry = 0;
            }
        }

        if (i >= 0) {
            if (carry == 1) {
                res = addBinary(a.substring(0, i + 1), "1") + res;
                return res;
            }
            res = a.substring(0, i + 1) + res;
        }
        if (j >= 0) {
            if (carry == 1) {
                res = addBinary(b.substring(0, j + 1), "1") + res;
                return res;
            }
            res = b.substring(0, j + 1) + res;
        }else if (carry == 1) {
            res = "1" + res;
        }
        return res;

    }*/
}
